from student import *


# stu为存储student类的对象的列表
def createFile(stuList):  # 建立初始的数据文件
    print("请初始化学生数据：")
    print("-" * 30)
    readStu(stuList)  # 调用student.py中的函数读入数据
    saveFile(stuList)
    return len(stuList)


def readFile(stuList):  # 将文件的内容读出置于对象列表stu中
    try:
        with open('student.txt', 'r', encoding="UTF-8") as file:
            for line in file.readlines():
                if line != "":
                    s = line.rstrip('\n').split(',')
                    num, name, gender = s[0], s[1], s[2]
                    score = {"语文": float(s[3]), "数学": float(s[4]), "英语": float(s[5])}
                    total, rank = float(s[6]), int(s[7])
                    oneStu = Student(num, name, gender, score, total, rank)
                    stuList.append(oneStu)
            return len(stuList)  # 返回记录条数
    except FileNotFoundError:
        print("数据文件不存在！")  # 若打开失败，输入提示信息
        return 0  # 因为数据文件不存在，返回0，表示无学生数据


def saveFile(stuList):  # 将对象列表的内容写入文件
    try:
        with open('student.txt', 'w', encoding="UTF-8") as file:
            tab = ','
            for oneStu in stuList:
                s = oneStu.getNum() + tab + oneStu.getName() + tab + oneStu.getGender() + tab + \
                    str(oneStu.getScore()['语文']) + tab + str(oneStu.getScore()['数学']) + \
                    tab + str(oneStu.getScore()['英语']) + \
                    tab + str(oneStu.getTotal()) + tab + str(oneStu.getRank()) + '\n'
                file.write(s)
    except IOError:
        print("文件打开错误！")  # 如果打开失败，输出信息
        exit(0)